import { cloneDeep } from 'lodash-es'
import { reactive } from 'vue'

export function useTable() {
    const gridOptions = reactive<any>({
        border: true,
        columnConfig: {
            resizable: true,
        },
        columns: [
            // { title: '', type: 'checkbox', width: '60' },
            { field: 'userName', title: '姓名' },
            { field: 'loginName', title: '登录名', width: 120 },
            { field: 'phonenumber', title: '手机号', width: 120 },
            { field: 'email', title: '邮箱' },
            { field: 'status', slots: { default: 'status' }, title: '账号状态', width: 80 },
            { field: 'updateTime', title: '最后修改时间' },
            { slots: { default: 'operate' }, title: '操作', width: 200 },
        ],
        data: [],
        editConfig: {
            mode: 'row',
            showStatus: true,
            trigger: 'manual',
        },
        height: 530,
        keepSource: true,
        loading: false,
        pagerConfig: {
            currentPage: 1,
            enabled: true,
            pageSize: 10,
            pageSizes: [10, 20, 50, 100, 200, 500],
            total: 0,
        },
        showOverflow: true,
    })

    const btns = [
        {
            label: '编辑',
            value: 'edit',
        },
        {
            label: '重置密码',
            value: 'resetPwd',
        },
    ]
    // 删除空属性
    const paramsIsNull = (obj: any) => {
        const _newPar = {}
        for (const key in obj) {
            if (
                (obj[key] === 0 || obj[key])
                && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== ''
            )
                _newPar[key] = obj[key]
        }
        // 返回新对象
        return _newPar
    }

    // TODO:多条件查询方法 仅字符串对比 模糊匹配
    const useQuery = (data: any, params: any) => {
        const notNullParams = paramsIsNull(params)
        return data.filter((item) => {
            return Object.keys(notNullParams).every((key: string) => {
                // eslint-disable-next-line unicorn/prefer-includes
                const flag = item[key] ? item[key].indexOf(notNullParams[key]) !== -1 : false
                return (
                    item[key] !== undefined
                    && flag
                )
            })
        })
    }

    // 前端分页
    const usePage = (data: any, gridOptions: any) => {
        const { currentPage, pageSize } = gridOptions.pagerConfig
        const val = cloneDeep(data)
        const list = val.splice((currentPage - 1) * pageSize, pageSize)
        return {
            list,
            total: data.length,
        }
    }

    return { btns, gridOptions, usePage, useQuery }
}
